package com.c.ctgproject.ui.storage.car

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.storage.VehicleInspectionAdapter
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.storage.VehicleInspectionEntity
import com.c.ctgproject.ui.vehicleinspection.VehicleInspectiontActivity
import com.c.ctgproject.utils.*
import kotlinx.android.synthetic.main.activity_file_car_wait_photographed.*
import org.jetbrains.anko.startActivity

/**
 *作者:LiBW
 *创建日期: 2020/11/3
 *描述: 待初检车辆列表 页面
 */
class VehicleInspectionListActivity : BaseActivity(), VehicleInspectionAdapter.CarCallback {
    private val mViewModel: VehicleInspectionListViewModel by lazy { ViewModelProvider(this)[VehicleInspectionListViewModel::class.java] }
    private var page = 1
    private var size = 20
    private var searchText = ""
    private val mList = ArrayList<VehicleInspectionEntity.DataBean.ListBean>()
    private val mAdapter: VehicleInspectionAdapter by lazy { VehicleInspectionAdapter(this, mList, this) }


    override fun event() {
        mCarRV.adapter = mAdapter
        mCarRV.layoutManager = LinearLayoutManager(this)
        mViewModel.result.observe(this, Observer {
            loading.dismiss()
            mRefresh.over()
            MyLog.d("待初检车辆列表:$it")
            handlerHttpResult(it) {
                val entity = getGson().fromJson(it, VehicleInspectionEntity::class.java).data
                entity?.list?.let { list ->
                    mList.addAll(list)
                    mAdapter.notifyDataSetChanged()
                }
            }
        })

        mViewModel.error.observe(this, Observer {
            loading.dismiss()
            mRefresh.over()
            MyLog.d("错误:$it")
            showToast(it)
        })
    }

    override fun click() {
        mSearchET.handlerText {
            if (it.isEmpty()) {
                searchText = ""
                mList.clear()
                page = 1
                getData()
            }
        }

        //搜索
        mSearchTV.setOnClickListener {
            searchText = mSearchET.text.toString()
            page = 1
            mList.clear()
            getData()
        }

        mRefresh.setOnLoadMoreListener {
            page++
            getData()
        }
        mRefresh.setOnRefreshListener {
            page = 1
            mList.clear()
            getData()
        }
    }

    override fun onResume() {
        super.onResume()
        page = 1
        searchText = ""
        mList.clear()
        getData()
    }

    private fun getData() {
        loading.show()
        mViewModel.getCarList(page, size, searchText)
    }

    override fun getLayout() = R.layout.activity_vehicle_inspectiont_list
    override fun onItemClick(ownerPlate: String) {
        startActivity<VehicleInspectiontActivity>("carPlate" to ownerPlate)
    }
}